<template>
    <!--  data:要展示的数据  -->
    <!--
        show-checkbox: 节点是否可以被选择
        node-key：每个树节点用来作为唯一标识的属性，整棵树应该是唯一的，其值为节点数据中的一个字段名
        default-expanded-keys：默认展开的节点的 key 的数组
    -->
    <div>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId" :default-expanded-keys="keys" ref="menuTree">
            <!-- slot-scope 表示的是获取子组件作用域中的元素，并且使用了 ES2015 的解构语法 -->
            <span class="custom-tree-node" slot-scope="{node, data}">
                <span>{{node.label}}</span>
                <span>
                    <!-- @click 是 v-on:click 的简写 -->
                    <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">Append</el-button>
                    <el-button type="text" size="mini" @click="edit(data)">Edit</el-button>
                    <el-button v-if="node.childNodes.length === 0" type="text" size="mini" @click="() => remove(node, data)">Delete</el-button>
                </span>
            </span>
        </el-tree>
        <!--
            close-on-click-modal: 是否可以通过点击 modal 关闭 Dialog
        -->
        <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
            <el-form :model="category">
                <el-form-item label="分类名称">
                    <el-input v-model="category.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="图标">
                    <el-input v-model="category.icon" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="计量单位">
                    <el-input v-model="category.productUnit" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitData">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            menus: [],
            // 当修改商品种类时，为 edit；当添加商品种类时，为 add
            // 添加和修改都要复用一个对话框
            dialogType: "",
            title: "",
            category: {
                name: "",
                parentCid: 0,
                catLevel: 0,
                showStatus: 1,
                sort: 0,
                catId : null,
                icon: "",
                productUnit: ""
            },
            keys: [],
            dialogVisible: false,
            // label: 指定节点标签为【节点对象】的某个属性值
            // children: 指定子树为【节点对象】的某个属性值
            defaultProps: {
                children: "children",
                label: "name"
            }
        };
    },
    methods: {
        getMenus: function(){
            this.$http({
                url: this.$http.adornUrl('/product/category/list/tree'),
                method: 'get'
            }).then(({data}) => {
                console.log("成功获取到菜单数据...", data.data);
                this.menus = data.data
            })
        },
        submitData: function(){
            if (this.dialogType === "add"){
                this.addCategory();
            }
            if (this.dialogType === "edit"){
                this.editCategory();
            }
        },
        edit(data){
            console.log("edit data: ", data);
            this.dialogType = "edit";
            this.title = "修改分类";
            this.dialogVisible = true;
            // 考虑到并发，可能有多个人正在对商品种类进行修改，因此需要先从服务器获取到最新的数据进行回显
            this.$http({
                url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
                method: 'get'
            }).then(({data}) => {
                console.log("要回显的数据: ", data);
                // 请求成功，回显最新的数据
                this.category.name = data.data.name;
                this.category.icon = data.data.icon;
                this.category.productUnit = data.data.productUnit;
                // 在更新种类信息的时候，需要用到 cat_id
                this.category.catId = data.data.catId;
                // 在更新当前种类信息之后，需要当前种类菜单的父菜单一直展开，所以需要获取 parent_cid
                this.category.parentCid = data.data.parentCid;
            });
        },
        append: function (data) {
            console.log("append ", data);
            this.dialogType = "add";
            this.title = "添加分类";
            this.category.parentCid = data.catId;
            this.category.catLevel = data.catLevel * 1 + 1;
            // 防止 edit 之后，之前的 category 信息还保存在 vue 组件中
            this.category.name = "";
            this.category.catId = null;
            this.category.icon = "";
            this.category.productUnit = "";
            this.dialogVisible = true;
        },
        remove(node, data){
            let ids = [data.catId];
            // ${var} 是与 `` 搭配使用的，是 js 的语法特性。{{var}} 是 vue 的语法特性，能够在 html 元素中插入组件属性
            this.$confirm(`此操删除菜单【${data.name}】, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http({
                    url: this.$http.adornUrl("/product/category/delete"),
                    method: 'post',
                    data: this.$http.adornData(ids, false)
                }).then(({data}) => {
                    this.$message({
                        message: "菜单删除成功",
                        type: "success"
                    });
                    // 刷新出新的菜单
                    this.getMenus();
                    // 设置需要默认展开的菜单
                    this.keys = [node.parent.data.catId]
                });
            }).catch(() => {});
            console.log("remove ", node, data);
        },
        editCategory(){
            let {catId, name, icon, productUnit} = this.category;
            let data = {catId, name, icon, productUnit};
            this.$http({
                url: this.$http.adornUrl("/product/category/update"),
                method: 'post',
                data: this.$http.adornData(data, false)
            }).then(({data}) => {
                this.$message({
                    message: "菜单修改成功",
                    type: "success"
                });
                this.dialogVisible = false;
                // 刷新出新的菜单
                this.getMenus();
                // 设置需要默认展开的菜单
                this.keys = [this.category.parentCid];
            });
        },
        addCategory(){
            this.$http({
                url: this.$http.adornUrl("/product/category/save"),
                method: 'post',
                data: this.$http.adornData(this.category, false)
            }).then(({data}) => {
                this.$message({
                    message: "菜单保存成功",
                    type: "success"
                });
                this.dialogVisible = false;
                // 刷新出新的菜单
                this.getMenus();
                // 设置需要默认展开的菜单
                this.keys = [this.category.parentCid];
            });
        },
        batchDelete: function(){
            // (leafOnly, includeHalfChecked) 接收两个 boolean 类型的参数：
            // 1. 是否只是叶子节点，默认值为 false
            // 2. 是否包含半选节点，默认值为 false
            let catIds = [];
            let checkedNodes = this.$refs.menuTree.getCheckedNodes(false, false);
            console.log("被选中的元素: ", checkedNodes);
            for (let i = 0; i < checkedNodes.length; i++){
                catIds.push(checkedNodes[i].catId);
            }
            this.$confirm(`是否批量删除【${catIds}】菜单?`,"提示",{
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.$http({
                    url: this.$http.adornUrl("/product/category/delete"),
                    method: 'post',
                    data: this.$http.adornData(catIds, false)
                }).then(({data}) => {
                    this.$message({
                        message: "菜单批量删除成功",
                        type: "success"
                    });
                    this.getMenus();
                });
            })
        }
    },
    created() {
        this.getMenus();
    }
};
</script>

<style scoped>
</style>
